﻿using Lonewolf.Entity;
using Lonewolf.Infrastructure;
using Lonewolf.IService;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lonewolf.Service
{
    public partial class AdminInfoService
    {
        private IAdminRoleService adminRole;
        private ILoginInfoService loginInfo;
        public AdminInfoService(EFDbContext dBContext, IAdminRoleService adminRole, ILoginInfoService loginInfo) : base(dBContext)
        {
            this.adminRole = adminRole;
            this.loginInfo = loginInfo;
        }
        public async Task<JsonResult<SaveEntity>> SaveAsync(AdminInfo admin, string password, string roleIds)
        {
            var result = new JsonResult<SaveEntity>();
            try
            {
                AdminInfo select;
                if (admin == null)
                    throw new ArgumentNullException(nameof(admin));
                if (password.IsNullOrEmpty() || roleIds.IsNullOrEmpty())
                {
                    result.message = Result.IsNull();
                    return result;
                }
                if (admin.Id.IsNullOrEmpty())//新增
                {
                    //第一步新增管理员基本信息(AdminInfo)
                    select=await Query().FirstOrDefaultAsync(p => p.LoginName == admin.LoginName);
                    if(select!=null)
                    {
                        result.success = false;
                        result.message = Result.Repeat();
                        return result;
                    }
                    var adminId = await InsertAsync(admin);
                    //第二步新增角色信息（AdminRole）
                    adminRole.SetRole(adminId, roleIds.ToStrArray());
                    //第三步新增Login信息
                    LoginInfo login = new LoginInfo()
                    {
                        UserId = adminId,
                        LoginPwd = password
                    };
                    bool lg = await loginInfo.SaveAsync(login);
                    if(lg!=true)
                    {
                        result.success = false;
                        result.message = Result.Wrong();
                        return result;
                    }
                       
                }
                else//修改
                {
                    
                    select = await Query().FirstOrDefaultAsync(p => p.Id == admin.Id);
                    if (select==null)
                    {
                        result.success = false;
                        result.message = Result.SelectNull();
                        return result;
                    }
                    else
                    {
                        select.LastChangeTime = DateTime.Now;
                        select.OrganizationId = admin.OrganizationId;
                        select.IsUse = admin.IsUse;
                        //Update(select);//因为Query()使用AsTracking跟踪实体，所以此处不需要执行修改流程
                        adminRole.SetRole(admin.Id, roleIds.ToStrArray());
                        LoginInfo login = await loginInfo.Query().FirstOrDefaultAsync(p => p.UserId == admin.Id);
                        if (login == null)
                        {
                            result.success = false;
                            result.message = Result.Wrong();
                            return result;
                        }
                        login.LoginPwd= password.DESEncrypt(login.LoginKey).MD5Encrypt();
                        login.LastChangeTime = DateTime.Now;
                    }
                }
                var flag = await SaveChangesAsync();
                result.success = flag;
                result.message = flag ? Result.Success(): Result.Error();
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.message = ex.Message;
            }
            return result;

        }

        public AdminInfo GetByAccount(string loginName)
        {
            try
            {
                return QueryNoTracking().FirstOrDefault(a => a.LoginName == loginName);
            }
            catch (Exception)
            {
                throw new ArgumentNullException(nameof(loginName));
            }
            
        }
        public async Task<JsonResult<CookieModel>> LoginAsync(string loginName, string password,string Ip)
        {
            var result = new JsonResult<CookieModel>();
            try
            {
                if (loginName.IsNullOrEmpty()||password.IsNullOrEmpty())
                {
                    result.message = "登录名和密码不能为空！";
                    return result;
                }
                else
                {
                    var adminEntity = await QueryNoTracking().FirstOrDefaultAsync(a=>a.LoginName==loginName);;
                    if (adminEntity==null)
                    {
                        result.message = "用户不存在！";
                        return result;
                    }
                    else
                    {
                        if (adminEntity.IsUse==true)
                        {
                            var loginEntity = await loginInfo.Query().FirstOrDefaultAsync(a=>a.UserId==adminEntity.Id);
                            if (loginEntity==null)
                            {
                                result.message = "未匹配到帐号数据，登录失败！";
                                return result;
                            }
                            else
                            {
                                string NowPassword = password.DESEncrypt(loginEntity.LoginKey).MD5Encrypt();
                                if (NowPassword!= loginEntity.LoginPwd)
                                {
                                    result.message = "密码错误，请重新登录！";
                                    return result;
                                }
                                else
                                {
                                    loginEntity.LoginNumber += 1;
                                    loginEntity.LastLoginTime = loginEntity.LoginTime;
                                    loginEntity.LoginTime = DateTime.Now;
                                    loginEntity.LoginIp = Ip;
                                    var flag = await SaveChangesAsync();
                                    result.success = flag;
                                    result.message = flag ? "登录成功！" : "登录失败！";
                                    result.Entity = new CookieModel
                                    {
                                        Id=adminEntity.Id,
                                        UserName=adminEntity.LoginName
                                    };
                                }
                            }
                        }
                        else
                        {
                            result.message = "此帐号已经被禁用，请联系管理员！";
                            return result;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result.code = 500;
                result.message = ex.Message;
            }
            return result;
        }
    }
}
